class TagsController < ApplicationController
  before_action :set_tag, only: [:show, :edit, :update, :destroy]
  before_action :get_page, only: [:show]
  before_action :confirm_authorization!, only: [:new, :edit, :update, :destroy]
  before_action :is_root_tag, only: [:create, :update]

  # GET /tags
  # GET /tags.json
  def index
    @title = '标签广场'
    @tags = Tag.all
  end

  # GET /tags/1
  # GET /tags/1.json
  def show
    @title = @tag.name
    @topics = @tag.topics.page get_page
  end

  # GET /tags/new
  def new
    @tag = Tag.new
  end

  # GET /tags/1/edit
  def edit
  end

  # POST /tags
  # POST /tags.json
  def create
    @tag = Tag.new(tag_params)

    respond_to do |format|
      if @tag.save
        format.html { redirect_to @tag, notice: 'Tag was successfully created.' }
        format.json { render :show, status: :created, location: @tag }
      else
        format.html { render :new }
        format.json { render json: @tag.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /tags/1
  # PATCH/PUT /tags/1.json
  def update
    respond_to do |format|
      if @tag.update(tag_params)
        format.html { redirect_to @tag, notice: 'Tag was successfully updated.' }
        format.json { render :show, status: :ok, location: @tag }
      else
        format.html { render :edit }
        format.json { render json: @tag.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tags/1
  # DELETE /tags/1.json
  def destroy
    @tag.destroy
    respond_to do |format|
      format.html { redirect_to tags_url, notice: 'Tag was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_tag
    @tag = Tag.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def tag_params
    params[:tag].permit(:name, :intro, :parent_id)
  end

  def confirm_authorization!
    redirect_to root_path unless (can? :manage, Tag)
  end

  def is_root_tag
    if params[:root_tag] == '1'
      params[:tag][:parent_id] = nil
    end
  end

end
